<?php

class Silk_Tms_Adminhtml_ShippingController extends Mage_Adminhtml_Controller_Action
{
    public function indexAction()
    {
        $this->_title($this->__("轻松老板"));
        $this->_title($this->__("运单管理"));
        $this->_initAction();
        $this->_addContent($this->getLayout()->createBlock('tms/adminhtml_shipping'));
        $this->renderLayout();
    }

    protected function _initAction()
    {
        $this->loadLayout()->_setActiveMenu("tms/shipping")->_addBreadcrumb(Mage::helper("adminhtml")->__("运单管理"), Mage::helper("adminhtml")->__("运单管理"));

        return $this;
    }

    public function viewAction()
    {
        $shippingId = $this->getRequest()->getParam('id');
        $this->loadLayout();
        $this->renderLayout();
    }

    public function removeshippingAction()
    {
        $shippingIds = $this->getRequest()->getPost('ids');
        try {
            $model = $this->getShippingModel();
            $model->remove($shippingIds);

            Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("运单已取消！"));
        } catch (Exception $e) {
            if ($e->getCode() == Silk_Tms_Model_Shipping::ERROR_DEFAULT_CODE) {
                Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__($e->getMessage()));
            } else {
                Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("取消运单失败！"));
            }
        }

        $this->_redirect("*/*/index");
    }
    
    public function deletecheckedAction()
    {
        $orderIds = $this->getRequest()->getPost('order_id');
        $shippingId = $this->getRequest()->getPost('shipping_id');

        try {
            $model = $this->getShippingModel();
            $model->deleteOrders($orderIds, $shippingId);

            Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("删除订单成功！"));
        } catch (Exception $e) {
            if ($e->getCode() == Silk_Tms_Model_Shipping::ERROR_DEFAULT_CODE) {
                Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__($e->getMessage()));
            } else {
                Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("删除订单失败！"));
            }
        }

        return $this->_redirect("*/*/view", array('id' => $shippingId));
    }

    public function deleteAction()
    {
        $orderId = $this->getRequest()->getParam('id');
        $shippingId = $this->getRequest()->getParam('shippingid');

        try {
            $model = $this->getShippingModel();
            $model->deleteOrders($orderId, $shippingId);

            Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("删除订单成功！"));
        } catch (Exception $e) {
            if ($e->getCode() == Silk_Tms_Model_Shipping::ERROR_DEFAULT_CODE) {
                Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__($e->getMessage()));
            } else {
                Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("删除订单失败！"));
            }
        }

        return $this->_redirect("*/*/view", array('id' => $shippingId));
    }

    public function updateshippingAction()
    {

        $shippingId = $this->getRequest()->getParam('shipping_id');
        $orderIds = Mage::getSingleton("core/session")->getData("add_orderids");

        $model = $this->getShippingModel();

        $allowStatus = array(
            Silk_Tms_Helper_Status::STATUS_SHIPPING_NEW,
            Silk_Tms_Helper_Status::STATUS_SHIPPING_ASSIGNED,
            Silk_Tms_Helper_Status::STATUS_SHIPPING_SORTED,
        );
        $shippingmodel = $this->getShippingModel()->load($shippingId);


        //add by wanglin start 运单分拣完成已锁定
        $shippinginfo=  Mage::getModel('tms/shipping')->load($shippingId);
        $addflag = $this->getRequest()->getParam('addflag');
        if(in_array($shippingmodel->getStatus(),$allowStatus) && $addflag!=1 && $shippinginfo->getLock()==0){
            $shippingmodel->setStatus(Silk_Tms_Helper_Status::STATUS_SHIPPING_ASSIGNED);
            $shippingmodel->save();
        }
        ////add by wanglin end

       /* if(in_array($shippingmodel->getStatus(),$allowStatus)){
            $shippingmodel->setStatus(Silk_Tms_Helper_Status::STATUS_SHIPPING_ASSIGNED);
            $shippingmodel->save();
        }*/

        try {
            $model->addOrdersToShipping($orderIds, $shippingId);
            Mage::getSingleton("core/session")->unsetData("add_orderids");
            Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("运单更新成功！"));
        } catch (Exception $e) {
            if ($e->getCode() == Silk_Tms_Model_Shipping::ERROR_DEFAULT_CODE) {
                Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__($e->getMessage()));
            } else {
                Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("运单更新失败！"));
            }

            return $this->_redirect("*/*/index");
        }

        $this->_redirect("*/*/view", array('id' => $shippingId));
    }

    public function showbinduserAction()
    {
        $shippingIds = $this->getRequest()->getPost('ids');
        if (!is_array($shippingIds)) {
            $shippingIds = array((int)$shippingIds);
        }

        try {
            foreach ($shippingIds as $shippingId) {
                $shipping = $this->getShippingModel();
                $shipping->validateShipping($shippingId);
            }
        } catch (Exception $e) {
            Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__($e->getMessage()));
            return $this->_redirect('*/*/index');
        }

        if ($shippingIds) {
            $shippingIds = implode(',', $shippingIds);

            Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("请选择配送人员！"));
            $this->_redirect("admin_zgb/adminhtml_warehouse/index", array('shippingId' => $shippingIds));
        } else {
            Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("运单未找到！"));
            $this->_redirect("*/*/index");
        }
    }

    public function cancelShippingUserAction()
    {
        $shippingId = $this->getRequest()->getPost('shipping_id');

        try {
            $model = $this->getShippingModel();
            $model->unbind($shippingId);

            Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("运单解除绑定成功！"));
        } catch (Exception $e) {
            Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__($e->getMessage()));
            return $this->_redirect("*/*/index");
        }

        return $this->_redirect("*/*/view", array('id' => $shippingId));
    }

    public function shippingbindAction()
    {
        $userId = $this->getRequest()->getParam('userId');
        $shippingId = $this->getRequest()->getParam('shippingId');
        
        //add by wanglin start  配送员24小时之前的所有运单里面的所有订单如果不是全部完成状态，不允许给他再分配运单
        /*$ondays = date('Y-m-d H:i:m',strtotime('-1day'));
        $tms_all = Mage::getModel('tms/shipping')->getCollection()
        ->addFieldToSelect('*')
        ->addFieldToFilter('user_id', array('eq' => $userId))
        ->addFieldToFilter('updated_at', array('lt' => $ondays));
        foreach ($tms_all as $tms_item) {
        	$orders = Mage::getModel('tms/shipping_order')->getCollection()
        	->addFieldToFilter('shipping_id', array('eq' => $tms_item->getId()));
        	foreach ($orders as $order) {
                $orderItem =  Mage::getModel('sales/order')->load($order->getOrderId());
        		if($orderItem->getStatus() == 'complete_delivering' || $orderItem->getStatus() == 'pending' || $orderItem->getStatus() == 'processing' || $orderItem->getStatus() == 'complete_ship'){
        		    Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("配送员还有超过24小时未完成的订单，不允许再分配订单！"));
        			return $this->_redirect("*\/*\/index");
        		}
        	}
        }*/
        //add by wanglin end
        
        try {
            $model = $this->getShippingModel();
            $model->bind($userId, $shippingId);

            Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("运单分配成功！"));
        } catch (Exception $e) {
            if ($e->getCode() == Silk_Tms_Model_Shipping::ERROR_DEFAULT_CODE) {
                Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__($e->getMessage()));
            } else {
                Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("分配配送员失败！"));
            }
        }

        return $this->_redirect("*/*/index");
    }

    public function createAction()
    {
        $orderIds = $this->getRequest()->getParam('order_ids');
        $post = $this->getRequest()->getPost();
        try {
            $model = $this->getShippingModel();
            $shipping = $model->create($orderIds, $post);

            Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("运单创建成功！请分配到配送人员。"));
        } catch (Exception $e) {
            if ($e->getCode() == Silk_Tms_Model_Shipping::ERROR_DEFAULT_CODE) {
                Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__($e->getMessage()));
            } else {
                Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("运单创建失败！"));
            }
            return $this->_redirect("*/*/index");
        }

        $this->_redirect("zgb/adminhtml_warehouse/index", array("shippingId" => $shipping->getId()));
    }

    public function cancelAction()
    {
        $shippingId = $this->getRequest()->getParam('shipping_id');
        $shipping = Mage::getModel('tms/shipping')->load($shippingId);
        // 暂不开启事务
        // $connection = Mage::getSingleton('core/resource')->getConnection('core_write');

        if ($shipping && $shipping->getId()) {
            try {
                $shipping->setStatus('canceled');
                $shipping->save();
                $orders = Mage::getModel('tms/shipping_order')
                    ->addFieldToFilter('shipping_id', array('eq' => $shippingId));

                foreach ($orders as $order) {
                    $order->setShippingId(0);
                    $order->save();
                }
            } catch (Exception $e) {
                Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__($e->getMessage()));
            }
        } else {
            Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("运单未找到！"));
        }
    }

    public function getShippingId()
    {
        return $this->getRequest()->getParam('id');
    }

    public function pickupAllAction()
    {
        $id = $this->getRequest()->getParam('id');
        $shipping = Mage::getModel('tms/shipping')->load($id);
        $orders = Mage::getModel('tms/shipping_order')->getCollection()
            ->addFieldToSelect('*')
            ->addFieldToFilter('shipping_id', array('eq' => $shipping->getId()));

        foreach ($orders as $shipOrder) {
            try {
                $incrementId = $shipOrder->getIncrementId();

                $order = Mage::getModel('tms/shipping_order')->load($incrementId, 'increment_id');
                if ($order && $order->getId()) {
                    $mageOrder = Mage::getModel('sales/order')->load($order->getOrderId());
                }
                if(!$mageOrder->hasShipments()){
                    /** @var Silk_Tms_Helper_Pickup $helper */
                    $helper = Mage::helper('tms/pickup');

                    $helper->pickup($incrementId);
                }else{
                    $order->setStatus(Silk_Tms_Helper_Status::STATUS_ORDER_PICKED);
                    $order->save();
                }

                Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("全部取货成功！"));
            } catch (Exception $e) {
                Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
            }
        }
        $this->_redirect("*/*/view", array('id' => $id));
    }
    
    //add by wanglin start
    public function startshippingAction()
    {
    	$shippingId = $this->getRequest()->getParam('id');
    	if (!$shippingId) {
    		 Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("运单号不存在！"));
    		 $this->_redirect("*/*/view", array('id' => $shippingId));
    	}
    	$shipping = Mage::getModel('tms/shipping')->load($shippingId);
    	if (!$shipping || !$shipping->getId()) {
    		Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("运单不存在！"));
    		$this->_redirect("*/*/view", array('id' => $shippingId));
    	}
    	if ($shipping->getStatus() != Silk_Tms_Helper_Status::STATUS_SHIPPING_SORTED) {
    		Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("运单还未分拣完成！"));
    		$this->_redirect("*/*/view", array('id' => $shippingId));
    	}
    	$collection = Mage::getModel('tms/shipping_order')->getCollection()
    	->addFieldToFilter('shipping_id', array('eq' => $shippingId))
    	->addFieldToFilter('status', array('eq' => Silk_Tms_Helper_Status::STATUS_ORDER_NEW));
    	if ($collection->getSize() > 0) {
    		Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("运单中还有订单未取货！"));
    		$this->_redirect("*/*/view", array('id' => $shippingId));
    	}else{
    		$shipping->setStatusDelivering();
    		if (!$shipping->isLock()) {
    			$shipping->setLock(1);
    		}
    		$transactionSave = Mage::getModel('core/resource_transaction');
    		$orders = $this->getShippingOrderCollection($shippingId);
    		foreach ($orders as $order) {
    			$order->setStatus(Silk_Tms_Helper_Status::STATUS_ORDER_DELIVERING);
    			$transactionSave->addObject($order);
    		}
    		$transactionSave->addObject($shipping);
    		try {
    			$transactionSave->save();
    		} catch (Exception $e) {
    			Mage::getSingleton("adminhtml/session")->addError(Mage::helper("adminhtml")->__("发货失败！"));
    			$this->_redirect("*/*/view", array('id' => $shippingId));
    		}
    		$this->_redirect("*/*/view", array('id' => $shippingId));
    	}
    	
    	
    }
    
    protected function getShippingOrderCollection($shippingId = null)
    {
    	if ($shippingId == null)
    		$shippingId = $this->getShippingId();
    
    	/** @var Silk_Tms_Model_Mysql4_Shipping_Order_Collection $collection */
    	$collection = Mage::getModel('tms/shipping_order')->getCollection()
    	->addFieldToFilter('shipping_id', array('eq' => $shippingId))
    	->setOrder("status='complete_order'", 'ASC')
    	->setOrder("status='delivered'", 'ASC');
    
    	return $collection;
    }
    //add by wanglin end
    
    

    public function changeAction()
    {
        $id = $this->getRequest()->getPost('shipping_id');
        $regionId = $this->getRequest()->getPost('region_id');
        $carId = $this->getRequest()->getPost('car_id');
        $sorts = $this->getRequest()->getPost('sort');
        /** @var Mage_Core_Model_Resource_Transaction $transactionSave */
        $transactionSave = Mage::getModel('core/resource_transaction');

        foreach ($sorts as $orderId => $sort) {
            /** @var Silk_Tms_Model_Shipping_Order $order */
            $order = Mage::getModel('tms/shipping_order')->load($orderId, 'order_id');
            if ($order && $order->getId() && $order->getShippingId() == $id) {
                $order->setSort((int)$sort);
                $transactionSave->addObject($order);
            }
        }

        $shipping = Mage::getModel('tms/shipping')->load($id);
        $shipping->setRegionId($regionId);
        $shipping->setCarId($carId);
        $transactionSave->addObject($shipping);

        try {
            $transactionSave->save();
        } catch (Exception $e) {
            Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
            return $this->_redirect("*/*/view", array('id' => $id));
        }

        Mage::getSingleton("adminhtml/session")->addSuccess('运单信息已修改！');
        $this->_redirect("*/*/view", array('id' => $id));
    }

    protected function _isAllowed()
    {
        return Mage::getSingleton('admin/session')->isAllowed('sales/shipping');
    }

    public function printAction()
    {
        $this->loadLayout();
        $this->renderLayout();
    }

    /**
     * @return Silk_Tms_Model_Shipping
     */
    protected function getShippingModel()
    {
        /** @var Silk_Tms_Model_Shipping $model */
        $model = Mage::getModel('tms/shipping');

        return $model;
    }

    public function lockAction(){
        $id = $this->getRequest()->getParam('shipping_ids');
        try{
            Mage::getModel("tms/shipping")->lock($id);
            Mage::getSingleton("adminhtml/session")->addSuccess("操作成功");
        }catch(Exception $e){
            Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
        }
        $this->_redirect("*/*/index");
    }
    public function unlockAction(){
        $ids = $this->getRequest()->getParam('shipping_ids');
        if(!is_array($ids)){
            $model = Mage::getModel('tms/shipping')->load($ids);
            if($model->getStatus()=="delivering"){
                Mage::getSingleton("adminhtml/session")->addError("运单在配送中，不能解锁");
               return $this->_redirect("*/*/view",array("id"=>$ids));
            }
        }else{
            $error = false;
            foreach ($ids as $id) {
                $model = Mage::getModel('tms/shipping')->load($id);
                if($model->getStatus()=="delivering"){
                    $error = true;
                }
            }
            if($error){
                Mage::getSingleton("adminhtml/session")->addError("操作中的运单有运单在配送中不能解锁，请重新选择");
                return $this->_redirect("*/*/index");
            }

        }
        try{
            Mage::getModel("tms/shipping")->unlock($ids);
            Mage::getSingleton("adminhtml/session")->addSuccess("操作成功");
        }catch(Exception $e){
            Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
        }
        $this->_redirect("*/*/index");

    }

    public function pickupSuccessAction()
    {
        $id = $this->getRequest()->getParam('id');
        try{
            Mage::getModel("tms/shipping")->pickupSuccess($id);
            Mage::getSingleton("adminhtml/session")->addSuccess("操作成功");
        }catch(Exception $e){
            Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
        }
        $this->_redirect("*/*/index");
    }
}
